from sqlalchemy import Column, DateTime, Enum, ForeignKey, Integer, String, func
from sqlalchemy.orm import relationship

from app.database.enums import ServerPrivacy, ServerType
from app.database.models.base import Base
from app.database.models.m2ms import server_categories


class Server(Base):
    __tablename__ = "server"

    id = Column(Integer, primary_key=True)
    name = Column(String(255))
    description = Column(String(255))
    ip_address = Column(String(100), nullable=False)
    inner_ip_address = Column(String(100), nullable=False)
    apache_port = Column(String(100), nullable=False)
    config_path = Column(String(50), nullable=False)
    proxy_type = Column(Enum(ServerType), nullable=False)
    proxy_privacy = Column(Enum(ServerPrivacy), nullable=False)
    provider = relationship("ProxyProvider", back_populates="servers")
    provider_id = Column(Integer, ForeignKey("provider.id"), nullable=False)
    ssh_port = Column(Integer, nullable=False)
    categories = relationship(
        "Category", secondary=server_categories, back_populates="servers"
    )
    login = Column(String(100), nullable=False)
    password = Column(String(100), nullable=False)
    country = relationship("Country", back_populates="servers")
    country_id = Column(Integer, ForeignKey("country.id"), nullable=False)
    proxies = relationship("Proxy", back_populates="server")
    status = Column(
        Enum("active", "inactive", "connection failure"), server_default="active"
    )
    was_added = Column(DateTime, server_default=func.now())

    def __str__(self):
        return self.ip_address

    def __repr__(self):
        return f"<Server №{self.id} {self.ip_address}>"
